﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace CPPEI.Coolzon.Tools.INSVideoTool
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        NamedPipeServerStream _pipeServer;
        public StreamWriter _pipeClientWriter;
        NamedPipeClientStream _pipeClient;

        public Dictionary<IntPtr, MainWindow> videoWindow = new Dictionary<IntPtr, MainWindow>();

        HideWindow _mainWindow;
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            WriteLog("INSVideo", "视频进程启动!");

            _mainWindow = new HideWindow();
            _mainWindow.WindowStartupLocation = WindowStartupLocation.Manual;
            _mainWindow.Left = -100;
            _mainWindow.Show();

            string[] args = e.Args;
            string pipeName = args[0];

            WriteLog("启动 PipeName:" + pipeName);

            if (!string.IsNullOrEmpty(pipeName))
            {
                try
                {
                    _pipeServer = new NamedPipeServerStream(string.Format("{0}DA", pipeName),
                        PipeDirection.In,
                        1,
                        PipeTransmissionMode.Message,
                        PipeOptions.Asynchronous);
                    ThreadPool.QueueUserWorkItem(PipeRunning);

                    _pipeClient = new NamedPipeClientStream("127.0.0.1", string.Format("{0}AD", pipeName), PipeDirection.Out);
                    _pipeClient.Connect();
                    _pipeClientWriter = new StreamWriter(_pipeClient);
                    _pipeClientWriter.AutoFlush = true;
                }
                catch
                {
                    _pipeServer = null;
                    _pipeClient = null;
                }
            }
        }

        #region pipe server running
        private void PipeRunning(object state)
        {
            if (this._pipeServer == null)
            {
                return;
            }
            this._pipeServer.BeginWaitForConnection((o) =>
            {
                NamedPipeServerStream server = (NamedPipeServerStream)o.AsyncState;
                server.EndWaitForConnection(o);
                StreamReader sr = new StreamReader(server);
                string result = null;
                string clientName = server.GetImpersonationUserName();
                while (true)
                {
                    result = sr.ReadLine();
                    if (result == null || result == "exit")
                    {
                        break;
                    }

                    WriteLog("result:" + result);
                    //cmd:p1,p2,p3
                    string[] ret = result.Split(new string[] { ":>" }, StringSplitOptions.None);
                    WriteLog("result:" + ret[0]);
                    if (ret != null && ret.Length > 1)
                    {
                        switch (ret[0].ToUpper())
                        {
                            case "SETCAMERA":
                                ChangeCameraID(ret[1]);
                                break;
                            case "OPENCAMERA":
                                OpenVideo(ret[1]);
                                break;
                            case "CLOSECAMERA":
                                CloseVideo(ret[1]);
                                break;
                        }
                    }
                }
                sr.Close();
                _pipeServer.Close();
                _pipeServer = null;
            }, this._pipeServer);
        }
        #endregion


        private void ChangeCameraID(string param)
        {
            try
            {
                string[] ret = param.Split(new char[] { ',' });
                IntPtr intPtr = new IntPtr(long.Parse(ret[0]));
                int cameraID = int.Parse(ret[1]);
                if (videoWindow.ContainsKey(intPtr))
                {
                    videoWindow[intPtr].Dispatcher.Invoke(() =>
                    {
                        videoWindow[intPtr].ChangeCameraID(cameraID);
                    });
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message + "\nParam:" + param);
            }
        }

        private void OpenVideo(string param)
        {
            lock (videoWindow)
            {
                try
                {
                    WriteLog("OpenVideo" + param);
                    _mainWindow.VideoParamList.Add(param);
                    //_mainWindow.Dispatcher.Invoke(() =>
                    //{
                    //    try
                    //    {
                    //        WriteLog(Environment.NewLine);
                    //        WriteLog("OpenVideo" + param);

                    //        string[] args = param.Split(new char[] { ',' });

                    //        MainWindow mainWindow = new MainWindow(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
                    //        mainWindow.LoadCompleted += mainWindow_LoadCompleted;
                    //        mainWindow.Show();

                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        WriteLog(Environment.NewLine + "错误1:" + ex.StackTrace + "\nParam:" + param);
                    //    }
                    //});
                }
                catch (Exception ex)
                {
                    WriteLog(Environment.NewLine + "错误:" + ex.StackTrace + "\nParam:" + param);
                }
            }
        }

        private void CloseVideo(string param)
        {
            try
            {
                WriteLog((string.Format("CloseVideo:{0}", param)));
                _mainWindow.ClosingList.Add(new IntPtr(long.Parse(param)));
                //IntPtr intPtr = new IntPtr(long.Parse(param));
                //if (videoWindow.ContainsKey(intPtr))
                //{
                //    _mainWindow.Dispatcher.Invoke(() =>
                //    {
                //        videoWindow[intPtr].Close();
                //    });
                //    videoWindow.Remove(intPtr);
                //    WriteLog((string.Format("CloseVideo成功:{0}", param)));
                //}
                //else
                //{
                //    WriteLog((string.Format("CloseVideo不存在列表中:{0}", param)));
                //}
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message + "\nParam:" + param);
            }
        }


        public void WriteLog(string message)
        {
            try
            {
                using (FileStream fs = new FileStream("C:\\INSVideoError.log", FileMode.Append))
                {
                    using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default))
                    {
                        sw.Write(Environment.NewLine);
                        sw.Write("{0}:\t{1}\n", DateTime.Now, message);
                        sw.Write(Environment.NewLine);
                    }
                }
            }
            catch
            {
            }
        }

        public void WriteLog(string param, string message)
        {
            try
            {
                using (FileStream fs = new FileStream("C:\\INSVideoError.log", FileMode.Append))
                {
                    using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default))
                    {
                        sw.Write(Environment.NewLine);
                        sw.Write("{0}:\t{1}\n", DateTime.Now, message);
                        sw.Write(Environment.NewLine);
                    }
                }
            }
            catch
            {
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            try
            {
                base.OnExit(e);
                foreach (var item in videoWindow)
                {
                    item.Value.Close();
                }
                WriteLog("视频进程关闭");
            }
            catch (Exception ex)
            {
                WriteLog("视频进程关闭异常:" + ex.StackTrace);
            }
        }
    }
}
